package com.may.wlrj.services;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.context.request.async.DeferredResult;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.may.wlrj.dao.OrganizationDAO;
import com.may.wlrj.entity.OrganizationEntity;
import com.may.wlrj.entity.UserEntity;
import com.may.wlrj.entity.UserLogEntity;
import com.may.wlrj.util.XinLongUtil;

@Service
@Transactional
public class OrganizationService {
	private Logger log = Logger.getLogger(OrganizationService.class);
	private OrganizationDAO orgDao;
	@Autowired
	public void setOrgDAO(OrganizationDAO orgDao) {
		this.orgDao = orgDao;
	}
	private ObjectMapper mapper = new ObjectMapper();
	
	public String InitOrgTree(HttpSession session) throws JsonProcessingException{ 
		UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
		ArrayNode rootnode = mapper.createArrayNode();  
		//获取根节点
		try{
			OrganizationEntity org_root = null;
			if(sentity.getUsername().equals("hzwlprevail")){
				org_root = orgDao.findByOrgcode("10001");
			}else{
				org_root = orgDao.findByOrgcode(orgDao.findCodeByID(sentity.getOrg_id()));
			}
			ObjectNode jnode = mapper.createObjectNode();
			jnode.put("title", org_root.getName());
			jnode.put("id", org_root.getId());
			jnode.put("orgcode", org_root.getOrgcode());
			jnode.put("leader", org_root.getLeader());
			jnode.put("address", org_root.getAddress());
			jnode.put("parent_name", org_root.getParent_name());				
			jnode.put("parent_id", org_root.getParentid());
			jnode.put("descriptor", org_root.getDescriptor());
			jnode.put("spread", true);
			if(org_root.getManager_id() !=null && !org_root.getManager_id().equals("")){
				jnode.put("manager_id", org_root.getManager_id());
				jnode.put("manager_name", orgDao.findNameByID(org_root.getManager_id()));					
			}
			jnode.put("iconCls", "icon-home");
			jnode.put("children",findSubNodes(org_root.getId(),org_root.getName()));
			rootnode.add(jnode);
		}catch(EmptyResultDataAccessException er){
			log.error("[Error]================没有找到机构根节点!");
			return mapper.writeValueAsString(rootnode);
		}catch(Exception e){
			log.error("[Error]================读取机构信息异常!");
			return mapper.writeValueAsString(rootnode);
		}  
          
		
		return mapper.writeValueAsString(rootnode);
	}
	
	@SuppressWarnings("deprecation")
	private ArrayNode findSubNodes(String treeid,String parentid) throws JsonProcessingException{
		List<OrganizationEntity> orglist = null;
		ArrayNode marksNode = mapper.createArrayNode();
		ObjectNode tnode = null;
		try{
			orglist = orgDao.findSubOrg(treeid);
			for(OrganizationEntity org : orglist){
				tnode = mapper.createObjectNode();
				tnode.put("title", org.getName());
				tnode.put("id", org.getId());
				tnode.put("orgcode", org.getOrgcode());
				tnode.put("leader", org.getLeader());
				tnode.put("address", org.getAddress());
				tnode.put("descriptor", org.getDescriptor());
				tnode.put("parent_name", org.getParent_name());				
				tnode.put("parent_id", org.getParentid());
				if(org.getManager_id() !=null && !org.getManager_id().equals("")){
					tnode.put("manager_id", org.getManager_id());
					tnode.put("manager_name", orgDao.findNameByID(org.getManager_id()));					
				}
				
				ArrayNode subNode = findSubNodes(org.getId(),org.getName());
				if(subNode.size() > 0){
					tnode.put("iconCls", "icon-institution");
					tnode.put("children", subNode);
				}else{
					tnode.put("iconCls", "icon-finance");
				}
				
				marksNode.add(tnode);
				
			}
		}catch(EmptyResultDataAccessException er){
			return marksNode;
		}
		
		return marksNode;
	}
	
	public String OrgTreeForTreeTable(HttpSession session) throws JsonProcessingException{ 
		UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
		ArrayNode rootnode = mapper.createArrayNode();  
		//获取根节点
		try{
			OrganizationEntity org_root = null;
			if(sentity.getUsername().equals("hzwlprevail")){
				org_root = orgDao.findByOrgcode("10001");
			}else{
				org_root = orgDao.findByOrgcode(orgDao.findCodeByID(sentity.getOrg_id()));
			}
			ObjectNode jnode = mapper.createObjectNode();
			jnode.put("title", org_root.getName());
			jnode.put("id", org_root.getId());
			jnode.put("orgcode", org_root.getOrgcode());
			jnode.put("leader", org_root.getLeader());
			jnode.put("address", org_root.getAddress());
			jnode.put("parent_name", org_root.getParent_name());	
			jnode.put("parent_id", org_root.getParentid());
			jnode.put("isMenu", 0);
			jnode.put("pid", 0);
			jnode.put("open", true);
			jnode.put("descriptor", org_root.getDescriptor());
			if(org_root.getManager_id() !=null && !org_root.getManager_id().equals("")){
				jnode.put("manager_id", org_root.getManager_id());
				jnode.put("manager_name", orgDao.findNameByID(org_root.getManager_id()));					
			}
			findSubNodesFortreeTable(org_root.getId(),jnode,rootnode);
			rootnode.add(jnode);
		}catch(EmptyResultDataAccessException er){
			log.error("[Error]================没有找到机构根节点!");
			return mapper.writeValueAsString(rootnode);
		}catch(Exception e){
			log.error("[Error]================读取机构信息异常!");
			return mapper.writeValueAsString(rootnode);
		}  
          
		
		return mapper.writeValueAsString(rootnode);
	}
	
	@SuppressWarnings("deprecation")
	private void findSubNodesFortreeTable(String treeid,ObjectNode jnode,ArrayNode marksNode) throws JsonProcessingException{
		List<OrganizationEntity> orglist = null;
		ObjectNode tnode = null;
		try{
			orglist = orgDao.findSubOrg(treeid);
			if(orglist.size() > 0) {
				jnode.put("isMenu", 0);
			}else {
				jnode.put("isMenu", 1);
			}
			for(OrganizationEntity org : orglist){
				tnode = mapper.createObjectNode();
				tnode.put("title", org.getName());
				tnode.put("id", org.getId());
				tnode.put("orgcode", org.getOrgcode());
				tnode.put("leader", org.getLeader());
				tnode.put("address", org.getAddress());
				tnode.put("descriptor", org.getDescriptor());
				tnode.put("parent_name", org.getParent_name());		
				tnode.put("parent_id", org.getParentid());
				tnode.put("pid", org.getParentid());
				if(org.getManager_id() !=null && !org.getManager_id().equals("")){
					tnode.put("manager_id", org.getManager_id());
					tnode.put("manager_name", orgDao.findNameByID(org.getManager_id()));					
				}
				
				findSubNodesFortreeTable(org.getId(),tnode,marksNode);				
				marksNode.add(tnode);
				
			}
		}catch(EmptyResultDataAccessException er){
			return ;
		}
		
		return;
	}
	
	public void _addOrganization(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request, HttpSession session) throws JsonProcessingException, IOException{
		XinLongUtil.xinLongUtil.printlog(log,jsonstr);
		UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
		String remoteaddr = XinLongUtil.getRemoteAddr(request);
		ObjectMapper mapper = new ObjectMapper();  
		ObjectNode res = mapper.createObjectNode();
    	com.fasterxml.jackson.databind.JsonNode rootNode = mapper.readTree(jsonstr);		
    	String orgcode =rootNode.get("orgcode").asText();
    	String orgname =rootNode.get("orgname").asText();
    	String parent_id =rootNode.get("parent_id").asText();
    	String manager_id =rootNode.get("manager_id").asText();
    	String address =rootNode.get("address").asText();    	
    	String leader =rootNode.get("leader").asText();
    	String descriptor =rootNode.get("descriptor").asText();
    	//权限判断
    	/*res = XinLongUtil.OptAuth("",jsonstr, sentity);
		if(!res.get("status").asText().equals("1210")){
    		return mapper.writeValueAsString(res);
		}*/
		Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("系统管理/机构管理/新增");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setMethod("addOrganization");
		ulog.setOrgid(sentity.getOrg_id());
		ulog.setCreate_check_userid(rootNode.get("ckname").asText());
    	try{
    		orgDao.findExist(orgname,orgcode);
    		res.put("status", "0");
			res.put("desc", "机构名称或机构编码已存在!");
			deferredResult.setResult(mapper.writeValueAsString(res));
			return;
    	}catch(EmptyResultDataAccessException er){
    		OrganizationEntity org = new OrganizationEntity();
        	org.setName(orgname);
        	org.setAddress(address);
        	org.setDescriptor(descriptor);
        	org.setLeader(leader);
        	org.setManager_id(manager_id);
        	org.setOrgcode(orgcode);
        	org.setCreatename(sentity.getUsername());
        	
        	org.setCreatetime(dateFormat.format(date));        	
        	org.setParentid(parent_id);
        	try{
        		
        		if(orgDao.saveorg(org) >0){
        			res.put("status", "1");
        			res.put("desc", "创建成功!");
        			ulog.setDescriptor("新建机构" + orgname + "-机构代码:" + orgcode);
        			ulog.setProceed("操作成功");
        			XinLongUtil.saveUserLog(ulog);
        		}else{
        			res.put("status", "0");
        			res.put("desc", "创建机构失败!");
        		}
        	}catch(EmptyResultDataAccessException ex){
        		res.put("status", "0");
        		res.put("desc", "找不到上级机构!");
        		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        	}
    	}
    	
    	deferredResult.setResult(mapper.writeValueAsString(res));
		return;
	}
	
	public void _editOrganization(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request, HttpSession session) throws JsonProcessingException, IOException{
		XinLongUtil.xinLongUtil.printlog(log,jsonstr);
		UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
		String remoteaddr = XinLongUtil.getRemoteAddr(request);
		ObjectMapper mapper = new ObjectMapper();  
		ObjectNode res = mapper.createObjectNode();
    	com.fasterxml.jackson.databind.JsonNode rootNode = mapper.readTree(jsonstr);		
    	String orgcode =rootNode.get("orgcode").asText();
    	String orgname =rootNode.get("orgname").asText();
    	String parent_id =rootNode.get("parent_id").asText();
    	String manager_id =rootNode.get("manager_id").asText();
    	String address =rootNode.get("address").asText();    	
    	String leader =rootNode.get("leader").asText();
    	String descriptor =rootNode.get("descriptor").asText();
    	//权限判断
    	/*res = XinLongUtil.OptAuth("",jsonstr, sentity);
		if(!res.get("status").asText().equals("1210")){
    		return mapper.writeValueAsString(res);
		}*/
		Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("系统管理/机构管理/修改");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setMethod("editOrganization");
		ulog.setOrgid(sentity.getOrg_id());
		ulog.setCreate_check_userid(rootNode.get("ckname").asText());
    	try{
    		orgDao.findNameExist(orgname,orgcode);
    		res.put("status", "0");
			res.put("desc", "机构名称已存在!");
			deferredResult.setResult(mapper.writeValueAsString(res));
			return;
    	}catch(EmptyResultDataAccessException er){   	
        	
        	try{
        		OrganizationEntity org = orgDao.findByOrgcode(orgcode);
        		if(org.getId().equalsIgnoreCase(parent_id)){
        			res.put("status", "0");
        			res.put("desc", "上级机构不能是自己!");
        			deferredResult.setResult(mapper.writeValueAsString(res));
        			return;
        		}
        		List<OrganizationEntity> orgs = orgDao.findSubOrgs(org.getId());
        		for(OrganizationEntity suborg : orgs){
        			if(suborg.getId().equals(parent_id)) {
        				res.put("status", "0");
            			res.put("desc", "上级机构不能是自己的下级!");
            			deferredResult.setResult(mapper.writeValueAsString(res));
            			return;
        			}
        		}
            	org.setName(orgname);
            	org.setAddress(address);
            	org.setDescriptor(descriptor);
            	org.setLeader(leader);
            	org.setManager_id(manager_id);
            	org.setOrgcode(orgcode);
            	org.setUpdatename(sentity.getUsername());
            	
            	org.setUpdatetime(dateFormat.format(date));
        		if(!org.getOrgcode().equals("10001")){
        			//顶级机构不修改父级ID
        			org.setParentid(parent_id);
        		}        		
        		if(orgDao.updateorg(org) >0){
        			res.put("status", "1");
        			res.put("desc", "修改成功!");
        			ulog.setDescriptor("修改机构" + orgname + "-机构代码:" + orgcode);
        			ulog.setProceed("操作成功");
        			XinLongUtil.saveUserLog(ulog);
        		}else{
        			res.put("status", "0");
        			res.put("desc", "修改机构失败!");
        		}
        	}catch(EmptyResultDataAccessException ex){
        		res.put("status", "0");
        		res.put("desc", "机构信息查找失败!");
        		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        	}
    	}
    	deferredResult.setResult(mapper.writeValueAsString(res));
		return;
	}
	
	public void _deleteOrganization(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request, HttpSession session) throws JsonProcessingException, IOException{
		XinLongUtil.xinLongUtil.printlog(log,jsonstr);
		UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
		String remoteaddr = XinLongUtil.getRemoteAddr(request);
		ObjectMapper mapper = new ObjectMapper();  
		ObjectNode res = mapper.createObjectNode();
    	com.fasterxml.jackson.databind.JsonNode rootNode = mapper.readTree(jsonstr);		
    	String orgcode =rootNode.get("orgcode").asText();
    	String orgid =rootNode.get("orgid").asText();
    	//权限判断
    	/*res = XinLongUtil.OptAuth("",jsonstr, sentity);
		if(!res.get("status").asText().equals("1210")){
    		return mapper.writeValueAsString(res);
		}*/
		Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("系统管理/机构管理/删除");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setMethod("deleteOrganization");
		ulog.setOrgid(sentity.getOrg_id());
		ulog.setCreate_check_userid(rootNode.get("ckname").asText());
    	try{
    		//判断机构下是否有用户
    		if(orgDao.isExistUser(orgid) > 0) {
    			res.put("status", "0");
    			res.put("desc", "该机构下有用户,无法删除!");
    			deferredResult.setResult(mapper.writeValueAsString(res));
    			return;
    		}
    		
    		//判断机构下是否有锁具
    		if(orgDao.isExistLock(orgid) > 0) {
    			res.put("status", "0");
    			res.put("desc", "该机构下有锁具,无法删除!");
    			deferredResult.setResult(mapper.writeValueAsString(res));
    			return;
    		}
    		
    		//判断机构下是否有钥匙
    		if(orgDao.isExistKey(orgid) > 0) {
    			res.put("status", "0");
    			res.put("desc", "该机构下有钥匙,无法删除!");
    			deferredResult.setResult(mapper.writeValueAsString(res));
    			return;
    		}
    		
    		int result = orgDao.delete(orgcode);
    		if(result == 0){
    			res.put("status", "0");
    			res.put("desc", "找不到该机构!");
    		}else if(result == 11){
    			res.put("status", "0");
    			res.put("desc", "该机构有关联数据,无法删除!");
    		}else{
    			res.put("status", "1");
    			res.put("desc", "修改成功!"); 
    			ulog.setDescriptor("删除机构,机构代码" + orgcode);
    			ulog.setProceed("操作成功");
    			XinLongUtil.saveUserLog(ulog);
    		}
    		   		
    	}catch(EmptyResultDataAccessException er){           	
    		res.put("status", "0");
			res.put("desc", "找不到该机构!");
    	}    	
    	
    	deferredResult.setResult(mapper.writeValueAsString(res));
		return;
	}
}
